package org.example.day03;

/**
 * 第二章节2.1.2.1：实例变量非线程安全(解决方式)
 */
public class MyThread3 {
    private int num = 0;
    //①添加了synchronized修饰实例方法，对象锁即this，线程e和f调用addI方法的都是m3对象，所以可以达到线程安全
    synchronized void addI(String username){
        try {
            if(username.equals("a")){
                num = 100;
                System.out.println("a set over");
                Thread.sleep(2000);
            }else {
                num = 200;
                System.out.println("b set over");
            }
            System.out.println(username + " num = " + num);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyThread3 m3 = new MyThread3();
        ThreadE te = new ThreadE(m3);
        te.start();
        ThreadF tf = new ThreadF(m3);
        tf.start();
    }
}

class ThreadE extends Thread{
    private MyThread3 m3;
    public ThreadE(MyThread3 m3){
        this.m3 = m3;
    }

    @Override
    public void run() {
        m3.addI("a");
    }
}

class ThreadF extends Thread{
    private MyThread3 m3;
    public ThreadF(MyThread3 m3){
        this.m3 = m3;
    }

    @Override
    public void run() {
        m3.addI("b");
    }
}

//synchronized修饰addI方法，达到线程安全
//a set over
//a num = 100
//b set over
//b num = 200